#!/usr/bin/env pwsh

# ZENrs 代码审核自动化脚本
# 此脚本用于检查Zig和Rust代码的质量、安全性和格式

Write-Host "=== ZENrs 代码审核工具 ==="
Write-Host "开始对代码进行自动审核...\n"

# 设置错误标志
$global:audit_failed = $false

# 错误处理函数
function Check-Error($stage) {
    if ($LASTEXITCODE -ne 0) {
        Write-Host "❌ $stage 失败！" -ForegroundColor Red
        $global:audit_failed = $true
    } else {
        Write-Host "✅ $stage 成功！" -ForegroundColor Green
    }
    Write-Host "-------------------------------\n"
}

# 1. 检查Zig代码
Write-Host "[1/5] 检查Zig代码格式..."
Push-Location "d:\编程项目\ZENrs\exokernel"
zig fmt --check src/
Check-Error "Zig代码格式检查"

# 2. 构建Zig代码
Write-Host "[2/5] 构建Zig exokernel代码..."
zig build
Check-Error "Zig代码构建"

# 3. 运行Zig测试
Write-Host "[3/5] 运行Zig测试..."
zig build test
Check-Error "Zig测试运行"
Pop-Location

# 4. 检查Rust代码
Write-Host "[4/5] 检查Rust代码..."
Push-Location "d:\编程项目\ZENrs\safe_services"

# 4.1 检查Rust代码格式
Write-Host "[4.1/5] 检查Rust代码格式..."
cargo fmt -- --check
Check-Error "Rust代码格式检查"

# 4.2 运行Clippy静态分析
Write-Host "[4.2/5] 运行Clippy静态分析..."
cargo clippy --all-targets --all-features -- -D warnings
Check-Error "Rust Clippy静态分析"

# 4.3 构建Rust代码
Write-Host "[4.3/5] 构建Rust代码..."
cargo check --all-targets
Check-Error "Rust代码构建检查"

# 4.4 运行Rust测试
Write-Host "[4.4/5] 运行Rust测试..."
cargo test
Check-Error "Rust测试运行"

# 4.5 安全审计（如果cargo-audit已安装）
Write-Host "[4.5/5] 运行依赖安全审计..."
if (Get-Command "cargo-audit" -ErrorAction SilentlyContinue) {
    cargo audit
} else {
    Write-Host "⚠️ cargo-audit 未安装，跳过依赖安全审计。可以通过 'cargo install cargo-audit' 安装。"
}
Pop-Location

# 5. 检查形式化验证文件
Write-Host "[5/5] 检查形式化验证文件..."
# 这里可以添加对TLA+文件的检查
if (Test-Path "d:\编程项目\ZENrs\formal_verification") {
    Write-Host "形式化验证目录存在，包含以下文件："
    Get-ChildItem -Path "d:\编程项目\ZENrs\formal_verification" -Recurse -Include "*.tla","*.md" | ForEach-Object {
        Write-Host "  - $($_.Name)"
    }
    Write-Host "✅ 形式化验证文件检查完成"
} else {
    Write-Host "⚠️ 形式化验证目录不存在"
}
Check-Error "形式化验证文件检查"

# 总结
Write-Host "\n=== 代码审核总结 ==="
if ($global:audit_failed) {
    Write-Host "❌ 代码审核失败！请修复上述问题后重新运行。" -ForegroundColor Red
    exit 1
} else {
    Write-Host "✅ 代码审核通过！所有检查项都已通过。" -ForegroundColor Green
    exit 0
}